package com.xmut.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xmut.mall.product.entity.CategoryBrandRelationEntity;
import com.xmut.mall.product.service.CategoryBrandRelationService;
import com.xmut.mall.product.utils.RespBean;
import com.xmut.mall.product.vo.AddBrandVo;
import com.xmut.mall.product.vo.EditBrandVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmut.mall.product.utils.PageUtils;
import com.xmut.mall.product.utils.Query;

import com.xmut.mall.product.dao.BrandDao;
import com.xmut.mall.product.entity.BrandEntity;
import com.xmut.mall.product.service.BrandService;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // 获取key
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.eq("brand_id", key).or().like("name", key);
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void updateDetail(BrandEntity brand) {
        // 保证冗余字段的数据一致
        this.updateById(brand);

        if (!StringUtils.isEmpty(brand.getName())) {

            // 同步更新其他关联表中的数据
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());

            // 更新其他关联
        }
    }

    /**
     * 根据分类的id获取与其关联的品牌
     *
     * @param cateId
     * @return
     */
    @Cacheable(value = {"Brand"}, key = "#root.methodName+#root.args[0]")
    @Override
    public List<BrandEntity> getBrandByCateId(Long cateId) {
        // 通过cateId查询品牌关联信息
        List<CategoryBrandRelationEntity> relations = categoryBrandRelationService.list(new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id", cateId));
        // 收集品牌的id
        List<Long> brandIds = relations.stream().map(CategoryBrandRelationEntity::getBrandId).collect(Collectors.toList());
        List<BrandEntity> brands;
        if (brandIds.isEmpty()) {
            // 如果是空那就不查了
            return null;
        } else {
            // 根据品牌的id获取品牌信息
            brands = this.baseMapper.selectBatchIds(brandIds);
        }

        return brands;
    }

    /**
     * 获取全部品牌
     *
     * @return
     */
    @Cacheable(value = "Brand", key = "#root.methodName")
    @Override
    public List<BrandEntity> getAllBrand() {
        return this.list();
    }

    /**
     * 获取品牌分页数据
     *
     * @param params
     * @return
     */
    @Override
    public RespBean getBrandPage(Map<String, Object> params) {
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();

        if(StringUtils.isNotEmpty(String.valueOf(params.get("name"))) && !String.valueOf(params.get("name")).equals("null")){
            queryWrapper.like("name",String.valueOf(params.get("name")));
        }

        if (String.valueOf(params.get("order")).equals("desc")) {
            queryWrapper.orderByDesc(String.valueOf(params.get("sort")));
        } else {
            queryWrapper.orderByAsc(String.valueOf(params.get("sort")));
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );

        return RespBean.success("获取成功", new PageUtils(page));
    }

    /**
     * 添加品牌
     * @param vo
     * @return
     */
    @Override
    public RespBean addBrand(AddBrandVo vo) {
        BrandEntity brand = new BrandEntity();
        brand.setName(vo.getName());
        brand.setDescript(vo.getDescript());
        brand.setLogo(vo.getLogo());
        brand.setShowStatus(1);
        brand.setSort(0);

        boolean save = this.save(brand);
        if(save){
            return RespBean.success("保存成功");
        }else {
            return RespBean.error("保存失败");
        }
    }

    /**
     * 修改品牌信息
     * @param vo
     * @return
     */
    @Override
    public RespBean editBrand(EditBrandVo vo) {
        BrandEntity brand = new BrandEntity();
        brand.setBrandId(vo.getBrandId());
        brand.setLogo(vo.getLogo());
        brand.setName(vo.getName());
        brand.setDescript(vo.getDescript());
        brand.setShowStatus(vo.getShowStatus());
        brand.setSort(vo.getSort());

        boolean save = this.updateById(brand);
        if(save){
            return RespBean.success("修改成功");
        }else {
            return RespBean.error("修改失败");
        }
    }

    /**
     * 禁用品牌
     * @param brandId
     * @return
     */
    @Override
    public RespBean disableBrand(Long brandId) {

        boolean update = this.update(new UpdateWrapper<BrandEntity>().eq("brand_id", brandId).set("show_status", 0));
        if(update){
            return RespBean.success("禁用成功");
        }else {
            return RespBean.error("禁用失败");
        }
    }

    /**
     * 启用该品牌
     * @param brandId
     * @return
     */
    @Override
    public RespBean enableBrand(Long brandId) {
        boolean update = this.update(new UpdateWrapper<BrandEntity>().eq("brand_id", brandId).set("show_status", 1));
        if(update){
            return RespBean.success("启用成功");
        }else {
            return RespBean.error("启用失败");
        }

    }

    /**
     * 删除品牌
     * @param brandId
     * @return
     */
    @Override
    public RespBean deleteBrand(Long brandId) {
        boolean b = this.removeById(brandId);
        if(b){
            return RespBean.success("删除成功");
        }else {
            return RespBean.error("删除失败");
        }

    }

}